package com.hmall.common.Interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头
        String UserId = request.getHeader("user-info");
        //2、存入线程工具
        if (ObjectUtil.isNotEmpty(UserId)){
            UserContext.setUser(Long.valueOf(UserId));
        }
        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //线程结束，移除用户
        UserContext.removeUser();
    }
}
